#include "server.h"

extern MYSQL* mySql;

//ls + 空值 ，直接展示当前ls目录下所有文件名
//ls + 目录名 ，展示当前目录下 某目录文件下的所有文件名
//ls + 文件名，展示当前文件信息
int LsDir(char* FileName, int userId, char* retMsg){
    int fileId;
    int ret = PathnameAnalyse(FileName, userId, &fileId);
    if(ret == DIR_NAME) {
        char querySentence[2048] = {0};
        sprintf(querySentence, 
                "select filename, type from filesystem where parent_id = %d  and owner_id = %d", 
                fileId, userId);
        ret = mysql_query(mySql, querySentence);
        if(ret != 0) {
            printf("query error: %s\n", mysql_error(mySql));
            return WRONG_PATHNAME;
        }
        MYSQL_RES* result = mysql_store_result(mySql);
        if(result == NULL) {
            printf("query error: %s\n", mysql_error(mySql));
            return WRONG_PATHNAME;
        }
        MYSQL_ROW row = mysql_fetch_row(result);
        while(row != NULL) {
            strcat(retMsg, row[0]);
            strcat(retMsg, " ");
            strcat(retMsg, row[1]);
            strcat(retMsg, "   ");
            row = mysql_fetch_row(result);
        }
        mysql_free_result(result);
        return 0;
    } else if(ret == FILE_NAME) {
        char querySentence[2048] = {0};
        sprintf(querySentence, 
                "select a.filename, a.filesize, b.username, a.md5 from filesystem as a left join user as b on a.ownerid = b.id where a.id = %d", 
                fileId);
        ret = mysql_query(mySql, querySentence);
        if(ret != 0) {
            printf("query error: %s\n", mysql_error(mySql));
            return -1;
        }
        MYSQL_RES* result = mysql_store_result(mySql);
        if(result == NULL) {
            printf("query error: %s\n", mysql_error(mySql));
            return -1;
        }
        MYSQL_ROW row = mysql_fetch_row(result);
        while(row != NULL) {
            strcat(retMsg, row[0]);
            strcat(retMsg, " ");
            strcat(retMsg, row[1]);
            strcat(retMsg, " ");
            strcat(retMsg, row[2]);
            strcat(retMsg, " ");
            strcat(retMsg, row[3]);
            row = mysql_fetch_row(result);
        }
        mysql_free_result(result);
        return 0;
    } else {
        return -1;
    }

}
